package com.test40_JDBC;

import com.test40_JDBC.util.JDBCUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Arrays;

/**
 * 数据批处理
 */
public class Demo04_ExecuteBatch {

    /**
     * 通过Statement接口实现数据批处理
     * 可以使用不同的SQL命令
     */
    @Test
    public void test1() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        Statement statement = conn.createStatement();
        statement.addBatch("INSERT INTO user (name) VALUES ('小李老师 - A')");  // 追加批处理
        statement.addBatch("INSERT INTO user (name) VALUES ('小李老师 - B')");
        statement.addBatch("UPDATE user SET name='沐言科技'");
        statement.addBatch("INSERT INTO user (name) VALUES ('小李老师 - C')");
        statement.addBatch("INSERT INTO user (name) VALUES ('小李老师 - D')");
        statement.addBatch("INSERT INTO user (name) VALUES ('小李老师 - E')");
        statement.addBatch("DELETE FROM user");
        int[] result = statement.executeBatch();    // 执行批处理
        System.out.println("【批处理的执行结果】" + Arrays.toString(result));
        JDBCUtil.closeConnection(conn);
    }

    /**
     * 通过PreparedStatement接口实现数据批处理
     * 必须使用相同的SQL命令
     */
    @Test
    public void test2() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        String sql = "INSERT INTO user (name) VALUES (?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        for (int x = 0; x < 10; x++) {
            preparedStatement.setObject(1, "李兴华 - " + x);
            preparedStatement.addBatch();
        }
        int[] result = preparedStatement.executeBatch();
        System.out.println("【批处理的执行结果】" + Arrays.toString(result));
        JDBCUtil.closeConnection(conn);
    }
}
